﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Logic;
using Entities;

namespace Presentation
{
	public partial class TaskDialogUpgradeDatabase : Form
	{
		public TaskDialogUpgradeDatabase()
		{
			InitializeComponent();
		}

		private void buttonAccept_Click(object sender, EventArgs e)
		{
			bool success = true;
			MovieBL bl = new MovieBL();
			GenreBL gbl = new GenreBL();
			List<Movie> movies = bl.ListMoviesOldWay();

			foreach (Movie m in movies)
			{
				string content = m.Title + ":" + Environment.NewLine;
				for (int i = 0; i < m.Genres.Count; i++)
				{
					Genre g = gbl.GetByName(m.Genres[i].Name);
					if (g != null)
					{
						if (bl.AddGenre(m, g))
							content += "\t" + g.Id + ": " + g.Name + Environment.NewLine;
						else
						{
							content += "\tError: Relationship with genre '" + m.Genres[i].Name + "' wasn't added" + Environment.NewLine;
							success = false;
						}
					}
					else
					{
						content += "\tError: Genre '" + m.Genres[i].Name + "' not found" + Environment.NewLine;
						success = false;
					}
				}
				content += "----------------------------------" + Environment.NewLine;
				textBoxLog.Text += content;
			}

			if (success)
			{
				Helper help = new Helper();
				help.DeleteOldGenres();
				help.UpgradeSchema();

				buttonAccept.Text = "Close";
				MessageBox.Show("Database upgraded successfully", "Database upgraded", MessageBoxButtons.OK, MessageBoxIcon.Information);
				Logic.Properties.Settings.Default.UpgradedDatabase = true;
				Logic.Properties.Settings.Default.Save();
				DialogResult = DialogResult.OK;
			}
			else
			{
				MessageBox.Show("There was an error upgrading the database.", "Error at upgrading database", MessageBoxButtons.OK, MessageBoxIcon.Error);
				DialogResult = DialogResult.Cancel;
			}
		}

		private void TaskDialogUpgradeDatabase_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (checkBoxCloseIfSuccess.Checked)
			{
				e.Cancel = false;
			}
			else
			{
				if (buttonAccept.Text == "Close")
					e.Cancel = false;
				else
					e.Cancel = true;
			}
		}
	}
}
